#include "startdialog.h"
#include "plugins/gsplugin.h"

#include <QTimer>
#include <QApplication>
#include <QDesktopWidget>
#include <QStatusBar>
#include <QPluginLoader>
#include <QObject>
#include <QtPlugin>
#include <QDebug>
#include <QDir>

StartDialog::StartDialog(QWidget *parent) :
    QDialog(parent)
{
    ui.setupUi(this);
    setWindowFlags(Qt::FramelessWindowHint | Qt::WindowTitleHint);

    loadingProgress = 0;
    ui.progressBar->setValue(0);
    connect(&timer, SIGNAL(timeout()), this, SLOT(updateProgress()));
    loadPlugins();
}

StartDialog::~StartDialog()
{

}

void StartDialog::loadPlugins()
{

    QDir path = QDir(qApp->applicationDirPath());    
    path.cd("plugins");
    path.cd("gspp");
    foreach(QFileInfo info,
            path.entryInfoList(QDir::Files |
                               QDir::NoDotAndDotDot |
                               QDir::NoSymLinks))
    {
        QPluginLoader *loader = new QPluginLoader(info.absoluteFilePath());
        GSPlugIn *plugin = qobject_cast<GSPlugIn *>(loader->instance());

        if( (plugin != NULL) && (checkPlugIns(plugin) == true) )
        {
             plugInSet.append(plugin);
             qDebug() << "Add Plugin:" << plugin->getMenuName();
        }
        else
             delete loader;
    }

    //loading plugins
    timer.start(5);
}

bool StartDialog::checkPlugIns(GSPlugIn *plugin)
{
    if(!plugin->getMenuName().isEmpty() &&
       !plugin->getDllName().isEmpty() )
    {
        return true;
    }

    return false;
}


QList<GSPlugIn*> StartDialog::getPlugIns()
{    
    return plugInSet;
}

void StartDialog::updateProgress()
{
     ui.progressBar->setValue(loadingProgress++);
     if(loadingProgress > 100)
     {
         loadingProgress = 100;
         timer.stop();

         int errorCode = 0;
         if(errorCode != 0)
         {
             this->reject(); //failure
         }
         else
         {
             this->accept(); //success
         }
     }
}
